# tt_server.rb
# contains the server launcher and main class
#
# Copyright (c) 2009 Alex Wilson
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

require "datafier"
require "webrick"
require "thread"
require "uuid"
require "tt_servlets"

# The Web server module
#
# Contains the glue between the library and the javascript frontend.
#
# Also contains session management since WEBrick's sessions are crappy.
#
# Author:: Alex Wilson <alex@rijidij.org>

module TTServer

include WEBrick

# Starts the webrick server with the given config and block
def TTServer.start_webrick(config = {})
	config.update(:BindAddress => "127.0.0.1", :Port => 12090)
	server = HTTPServer.new(config)
	yield server if block_given?
	['INT', 'TERM'].each {|sig| 
		trap(sig) { server.shutdown }	
	}
	server.start
end

end

include TTServer
include TTServer::Servlets

TTServer.start_webrick(:DocumentRoot => './') do |serv|
	UserSession.load
	Timetable::Course.load_all

	serv.mount '/load', LoaderServlet
	serv.mount '/loaded', LoaderServlet
	serv.mount '/loadable', LoadableServlet
	serv.mount '/control/stop', ControlServlet, 'stop'
	serv.mount '/fetch', FetcherServlet
	serv.mount '/json/tt', JSONTimetableServlet
	
	serv.mount '/session/new', NewSessionServlet
	serv.mount '/session/add', AddToSessionServlet
	serv.mount '/session/remove', RemoveFromSessionServlet
	serv.mount '/session/clear', ClearSessionServlet
	serv.mount '/session/json', JSONSessionServlet
	serv.mount '/session/ical', ICalSessionServlet
	serv.mount '/session/all', ListSessionServlet
	serv.mount '/session/name', NameSessionServlet
	
	serv.mount '/session/lock', LockSessionServlet
	serv.mount '/session/unlock', UnlockSessionServlet
	
	serv.mount '/session/optimise', OptimiseSessionServlet
	
	serv.mount '/json/optimise_options', OptimisationOptionsServlet
	
	serv.mount '/json/groups_in', JSONGroupsServlet
	serv.mount '/update_all', GlobalUpdateServlet
end

